<template>
  <div class="dashboard-container">
    <div class="container">
      <div class="title">
        <span>{{ id ? '修改优惠券' : '新增优惠券' }}</span>
      </div>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="优惠券标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入优惠券标题" />
        </el-form-item>
        <el-form-item label="副标题" prop="subTitle">
          <el-input v-model="form.subTitle" placeholder="请输入副标题" />
        </el-form-item>
        <el-form-item label="使用规则" prop="rules">
          <el-input type="textarea" v-model="form.rules" placeholder="请输入使用规则" :rows="4" />
        </el-form-item>
        <el-form-item label="支付金额(分)" prop="payValue">
          <el-input v-model.number="form.payValue" type="number" placeholder="请输入支付金额，单位为分" />
        </el-form-item>
        <el-form-item label="抵扣金额(分)" prop="actualValue">
          <el-input v-model.number="form.actualValue" type="number" placeholder="请输入抵扣金额，单位为分" />
        </el-form-item>
        <el-form-item label="优惠券类型" prop="type">
          <el-radio-group v-model="form.type">
            <el-radio label="0">普通券</el-radio>
            <el-radio label="1">秒杀券</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio label="1">上架</el-radio>
            <el-radio label="2">下架</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="库存" prop="stock">
          <el-input-number v-model.number="form.stock" :min="0" :step="1" />
        </el-form-item>
        <el-form-item label="生效时间" prop="beginTime">
          <el-date-picker
            v-model="form.beginTime"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="请选择生效时间"
            :default-time="'00:00:00'"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="失效时间" prop="endTime">
          <el-date-picker
            v-model="form.endTime"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="请选择失效时间"
            :default-time="'23:59:59'"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>
      <div class="btnBox">
        <el-button @click="back">返回</el-button>
        <el-button type="primary" @click="submitForm('form')">提交</el-button>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import { Component, Vue } from 'vue-property-decorator'
import { addVoucher, editVoucher, queryVoucherById } from '@/api/voucher'
import { Form as ElForm } from 'element-ui'

@Component({
  name: 'voucherAdd'
})export default class extends Vue {
  private id: string | null = null
  private form: any = {
    title: '',
    subTitle: '',
    rules: '',
    payValue: 0,
    actualValue: 0,
    type: '0',
    status: '1',
    stock: 0,
    beginTime: '',
    endTime: ''
  }
  private rules: any = {
    title: [
      { required: true, message: '请输入优惠券标题', trigger: 'blur' },
      { type: 'string', message: '优惠券标题必须是字符串', trigger: 'blur' }
    ],
    payValue: [
      { required: true, message: '请输入支付金额', trigger: 'blur' },
      { type: 'number', min: 0, message: '支付金额不能小于0', trigger: 'blur' }
    ],
    actualValue: [
      { required: true, message: '请输入抵扣金额', trigger: 'blur' },
      { type: 'number', min: 0, message: '抵扣金额不能小于0', trigger: 'blur' },
      { validator: (rule: any, value: number, callback: any) => {
          const payValue = this.form.payValue;
          if (typeof payValue !== 'number') {
            callback(new Error('支付金额必须是数字'));
            return;
          }
          if (value < payValue) {
            callback(new Error('抵扣金额不能小于支付金额'));
          } else {
            callback();
          }
        }, trigger: ['blur', 'change'] }
    ]
    ,
    stock: [
      { required: true, message: '请输入库存', trigger: 'change' },
      { type: 'number', min: 0, message: '库存不能小于0', trigger: 'change' }
    ],
    beginTime: [
      { required: true, message: '请选择生效时间', trigger: 'change' }
    ],
    endTime: [
      { required: true, message: '请选择失效时间', trigger: 'change' },
      { validator: (rule: any, value: string, callback: any) => {
          const begin = this.form.beginTime
          if (!begin || !value) return callback()
          if (new Date(value).getTime() <= new Date(begin).getTime()) {
            callback(new Error('失效时间必须大于生效时间'))
          } else {
            callback()
          }
        }, trigger: ['change'] }
    ]
  }

  created() {
    this.id = this.$route.query.id as string | null
    if (this.id) {
      this.getDetail()
    }
  }

  // 获取详情
  private async getDetail() {
    await queryVoucherById(this.id as string)
      .then(res => {
        if (res && res.data && res.data.code === 1) {
          const data = res.data.data
          this.form = {
            ...data,
            type: String(data.type),
            status: String(data.status)
          }
        } else {
          this.$message.error(res.data.msg || '获取优惠券详情失败')
        }
      })
      .catch(err => {
        this.$message.error('请求出错了：' + err.message)
      })
  }

  // 提交表单
  private submitForm(formName: string) {
    console.log('开始提交表单');
    (this.$refs[formName] as ElForm).validate((valid: boolean) => {
      console.log('表单验证结果:', valid);
      if (valid) {
          console.log('表单验证通过，准备提交数据:', this.form);
          const request = this.id ? editVoucher : addVoucher
          // 构建符合VoucherDTO格式的请求数据
          const requestData: any = {
            title: this.form.title,
            subTitle: this.form.subTitle,
            rules: this.form.rules,
            payValue: parseInt(this.form.payValue || 0, 10),
          actualValue: parseInt(this.form.actualValue || 0, 10),
            type: this.form.type,
            status: this.form.status,
            stock: parseInt(this.form.stock || 0, 10),
            beginTime: this.form.beginTime || undefined,
            endTime: this.form.endTime || undefined
          }
          if (this.id) {
            requestData.id = this.id
          }
          console.log('提交的请求数据:', requestData);
          console.log('即将发送请求到API...');
          request(requestData)
          .then(res => {
            console.log('API响应结果:', res);
            if (res && res.data && res.data.code === 1) {
              this.$message.success(this.id ? '修改成功' : '新增成功')
              this.back()
            } else {
              console.log('API响应失败:', res.data);
              this.$message.error(res.data.msg || (this.id ? '修改失败' : '新增失败'))
            }
          })
          .catch(err => {
            console.error('API请求错误详情:', {
              message: err.message,
              stack: err.stack,
              config: err.config
            });
            this.$message.error('请求出错了：' + (err.message || '未知错误'))
          })
      }
    })
  }

  // 返回
  private back() {
    this.$router.push('/voucher')
  }
}
</script>

<style lang="scss" scoped>
.dashboard-container {
  margin: 30px;

  .container {
    background: #fff;
    padding: 30px;
    border-radius: 4px;

    .title {
      font-size: 16px;
      color: #333;
      margin-bottom: 20px;
      padding-bottom: 10px;
      border-bottom: 1px solid #eee;
    }

    .btnBox {
      margin-top: 30px;
      text-align: center;

      button {
        margin: 0 10px;
      }
    }
  }
}
</style>